<template>
  <div class="main_box" v-loading="pageLoading">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="queryCode">
              <el-input v-model="filters.queryCode" clearable placeholder="平台/医检条码号"></el-input>
            </el-form-item>
            <!--<el-form-item prop="searchCode">
              <el-input v-model="filters.searchCode" clearable placeholder="查询号"></el-input>
            </el-form-item>-->
            <el-form-item prop="itemName">
              <el-input v-model="filters.itemName" clearable placeholder="送检项目"></el-input>
            </el-form-item>
            <el-form-item prop="patientQuery">
              <el-input v-model="filters.patientQuery" clearable placeholder="患者姓名/手机/身份证"></el-input>
            </el-form-item>
            <el-form-item prop="userId" v-if="userRole != 2">
              <el-select v-model="filters.userId" :clearable="true" filterable placeholder="收样员姓名">
                <el-option v-for="item in collectList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="hospitalId" v-if="userRole != 2">
              <el-select v-model="filters.hospitalId" @change="listOffice" filterable :clearable="true" placeholder="医院名称">
                <el-option v-for="item in hospitalList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="officeId">
              <el-select v-model="filters.officeId" @change="listDoctor" filterable :clearable="true" placeholder="科室名称">
                <el-option v-for="item in officeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="doctorId" v-if="userRole != 2">
              <el-select v-model="filters.doctorId" filterable :clearable="true" placeholder="医生名称">
                <el-option v-for="item in doctorList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="institutionId" v-if="userRole != 3">
              <el-select v-model="filters.institutionId" filterable :clearable="true" placeholder="医检名称">
                <el-option v-for="item in institutionList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <!--<InstitutionSelect @institutionId="getInstitutionId" :site="2"></InstitutionSelect>-->
            <el-form-item prop="reportState" v-if="userRole != 2 && userRole != 3">
              <el-select v-model="filters.reportState" :clearable="true" placeholder="报告单状态">
                <el-option v-for="item in reviewStatue" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="resultState">
              <el-select v-model="filters.resultState" :clearable="true" placeholder="结果状态">
                <el-option v-for="item in resultStatue" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="printState">
              <el-select v-model="filters.printState" :clearable="true" placeholder="打印状态">
                <el-option v-for="item in agenciesStatue" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <!--<br/><span>送检时间：</span>-->
            <el-form-item prop="date">
              <el-date-picker
                v-model="filters.date"
                :clearable="true"
                type="datetimerange"
                range-separator="至"
                start-placeholder="送检开始日期"
                end-placeholder="送检结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-form-item>
            <el-form-item prop="abnormalState" v-if="userRole == 1">
              <el-select v-model="filters.abnormalState" :clearable="true" placeholder="异常状态">
                <el-option v-for="item in abnormalStatue" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="applyId">
              <el-input v-model="filters.applyId" clearable placeholder="采样编号"></el-input>
            </el-form-item>
            <el-form-item prop="state" v-has="permissionResume">
              <el-select v-model="filters.state" :clearable="true" placeholder="状态">
                <el-option key="1" label="正常" value="1"></el-option>
                <el-option key="-1" label="已删除" value="-1"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="init" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAddBatch()" size="mini"> 批量新增</el-button>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleBatchImport()" size="mini"> 批量导入</el-button>

            <el-button size="mini" plain type="danger" icon="el-icon-suitcase" v-has="permissionBatchSetCollect" @click="handleClickBatchCollect">设置收样员</el-button>
            <el-button size="mini" plain type="success" icon="el-icon-printer" v-has="permissionBatchPrint" @click="handleClickBatchPrint">批量打印</el-button>
            <el-button size="mini" plain type="success" icon="el-icon-finished" v-has="permissionBatchDownload" @click="handleClickBatchDownload">批量下载</el-button>
            <el-button size="mini" plain type="success" icon="el-icon-upload" v-has="permissionBatchCreateResult" @click="handleClickBatchCreateResult()">批量生成结果</el-button>
            <el-button size="mini" plain type="info" icon="el-icon-folder" v-has="permissionExport" @click="handleClickExport(0)">导出</el-button>
            <el-button size="mini" plain type="info" icon="el-icon-folder-opened" v-has="permissionExport" @click="handleClickExport(1)">合并导出</el-button>
            <el-button size="mini" plain type="info" icon="el-icon-refresh" v-has="permissionRefreshItem" @click="handleClickRefreshItemName(1)">刷新项目</el-button>
            <el-button size="mini" plain type="warning" icon="el-icon-collection" @click="handleBatchModifyInstitution" v-has="permissionModifyInstitution">批量修改医检</el-button>
            <el-button size="mini" plain type="warning" icon="el-icon-chat-dot-square" v-has="permissionSendMessage" @click="hanldeSendMessage"> 短信通知 </el-button>
            <el-upload
              v-has="permissionStateExport"
              style="display: inline-block; margin-left: 10px"
              :action="importUrl"
              :on-change="handleChange"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
              :show-file-list="false"
              :auto-upload="false"
            >
              <el-button size="mini" plain type="warning" icon="fa fa-plus"> 状态导入 </el-button>
            </el-upload>

            <el-button style="margin-left: 10px" size="mini" plain type="warning" icon="el-icon-delete-solid" @click="handleBatchDelete" v-has="permissionBatchDelete">
              批量删除
            </el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table
        :data="reportList"
        @selection-change="changeSelect"
        @row-dblclick="handleClickPrint"
        highlight-current-row
        v-loading="listLoading"
        element-loading-text="数据加载中，请稍后..."
        empty-text="对不起，没有找到相关数据！"
        fit
        style="width: 100%"
      >
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column type="index" width="50px" align="center" label="序号"> </el-table-column>
        <el-table-column prop="reportBeginTime" label="送检时间" width="87"></el-table-column>
        <el-table-column prop="reportCode" label="编号" width="130">
          <template slot-scope="scope">
            <span v-if="scope.row.reportCode">
              {{ scope.row.reportCode }}
              <el-tooltip class="item" effect="dark" content="复制" placement="top">
                <el-button
                  class="copy_reportCode"
                  size="mini"
                  icon="el-icon-document-copy"
                  circle
                  plain
                  id="copyBtn"
                  :data-clipboard-text="scope.row.reportCode"
                  @click="copyReportCode()"
                ></el-button>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="searchCode" label="查询号"></el-table-column>-->
        <el-table-column width="120" align="center" label="姓名-性别-年龄">
          <template slot-scope="scope">
            <span>{{ scope.row.patientName }} - {{ formatSex(scope.row.patientSex) }} - {{ scope.row.patientAge }}</span>
          </template>
        </el-table-column>
        <el-table-column width="200" align="center" label="医院-科室-医生">
          <template slot-scope="scope">
            <span>{{ scope.row.hospitalName }} - {{ scope.row.officeName }} - {{ scope.row.doctorName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="institutionName" label="医检机构" width="180"></el-table-column>

        <el-table-column label="平台/医检条码号" width="130">
          <template slot-scope="scope">
            <span v-if="scope.row.myReportCode">
              {{ scope.row.myReportCode }}
              <el-tooltip class="item" effect="dark" content="复制" placement="top">
                <el-button
                  class="copy_myReportCode"
                  size="mini"
                  icon="el-icon-document-copy"
                  circle
                  plain
                  id="copyBtn"
                  :data-clipboard-text="scope.row.myReportCode"
                  @click="copyMyReportCode()"
                ></el-button>
              </el-tooltip>
            </span>
            <span v-if="scope.row.insReportCode">
              {{ scope.row.insReportCode }}
              <el-tooltip class="item" effect="dark" content="复制" placement="top">
                <el-button
                  class="copy_insReportCode"
                  size="mini"
                  icon="el-icon-document-copy"
                  circle
                  plain
                  id="copyBtn"
                  :data-clipboard-text="scope.row.insReportCode"
                  @click="copyInsReportCode()"
                ></el-button>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>

        <!--  show-overflow-tooltip 当字符长度大于单元格宽度时 省略 -->
        <el-table-column width="230" label="送检项目">
          <template slot-scope="scope">
            <span>
              {{ scope.row.itemName }}
              <el-tooltip class="item" effect="dark" content="复制" placement="top">
                <el-button
                  class="copy_itemName"
                  size="mini"
                  icon="el-icon-document-copy"
                  circle
                  plain
                  id="copyBtn"
                  :data-clipboard-text="scope.row.itemName"
                  @click="copyitemName()"
                ></el-button>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column width="90" align="center" label="检测/打印">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" :type="formatReportStateType(scope.row.reportState)">
                {{ formatReportState(scope.row.reportState) }}
              </el-tag>
              <el-tag size="mini" :type="formatPrintStateType(scope.row.printState)" effect="dark">
                {{ formatPrintState(scope.row.printState) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="reportState" label="检测状态" :formatter="formatReportState"></el-table-column>-->
        <!--<el-table-column prop="abnormalState" label="异常状态" :formatter="formatAbnormalState"></el-table-column>-->
        <el-table-column prop="reportEndTime" label="报告时间" width="87"></el-table-column>
        <el-table-column label="收样员" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.syUserName }}</span
            ><span v-if="scope.row.syUserLevel">({{ scope.row.syUserLevel }}级)</span>
          </template>
        </el-table-column>
        <el-table-column prop="createUserName" label="创建人" width="90"> </el-table-column>
        <el-table-column prop="createDate" label="创建时间" width="90"></el-table-column>

        <!--错位的问题，在操作前一个列要加上width-->
        <el-table-column prop="reportPrintTime" label="最新打印时间" width="87"></el-table-column>
        <el-table-column label="操作" width="180px" fixed="right" style="align-content: center">
          <template slot-scope="scope">
            <!--<el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
            <el-button v-has="permissionEdit" @click="handleClickEditor(scope.row)" size="mini">编辑</el-button>
            <el-button v-has="permissionUpStatus" @click="handleIsDisable(scope.row)" size="mini">删除</el-button>-->
            <el-button v-has="permissionPrint" v-if="scope.row.reportState === 20" @click="handleClickPrint(scope.row)" size="mini">打印</el-button>
            <el-button v-has="permissionDownload" v-if="scope.row.reportState === 20" @click="handleClickDownload(scope.row)" size="mini">下载</el-button>
            <el-dropdown trigger="click" size="small">
              <el-button type="primary"> <i class="fa fa-list-ul"></i>更多 </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-has="permissionCheck" @click.native="handleClickDetail(scope.row)">查看</el-dropdown-item>
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item>
                <el-dropdown-item v-has="permissionCollect" @click.native="handleClickCollect(scope.row)">收取</el-dropdown-item>
                <el-dropdown-item v-has="permissionDelivered" @click.native="handleClickDelivered(scope.row)">送达</el-dropdown-item>
                <el-dropdown-item v-has="permissionReceived" @click.native="handleClickReceived(scope.row)">确认收到</el-dropdown-item>
                <el-dropdown-item v-has="permissionUpload" @click.native="handleClickUpload(scope.row)">上传结果</el-dropdown-item>
                <el-dropdown-item v-has="permissionViewSpecimen" v-if="scope.row.syUserId" @click.native="handleClickViewSpecimen(scope.row)">查看标本箱</el-dropdown-item>
                <el-dropdown-item v-has="permissionBack" v-if="scope.row.reportState === 20" @click.native="handleClickBack(scope.row)">撤回结果</el-dropdown-item>
                <el-dropdown-item v-has="permissionFinanceRemark" @click.native="financeRemarkDialog(scope.row.reportId)"> 财务备注 </el-dropdown-item>

                <el-dropdown-item v-has="permissionUpStatus" v-if="scope.row.state === 1" @click.native="handleIsDisable(scope.row, -1)">删除</el-dropdown-item>
                <el-dropdown-item v-has="permissionResume" v-if="scope.row.state === -1" @click.native="handleIsDisable(scope.row, 1)">恢复</el-dropdown-item>
                <!--<el-dropdown-item v-has="permissionEdit" v-print="'#printDiv'" @click.native="handleClickPrint(scope.row)">打印</el-dropdown-item>
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickPrint(scope.row)">预览打印</el-dropdown-item>
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickDownload(scope.row)">下载</el-dropdown-item>
                <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">{{scope.row.state == 0? '启用' : '禁用'}}</el-dropdown-item>-->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具条 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100, 300, 500, 1000]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <BatchAddReport ref="batchAddReport"></BatchAddReport>
    <BatchImport ref="BatchImport"></BatchImport>
    <BatchEditCollect ref="batchEditCollect"></BatchEditCollect>
    <uploadFile ref="uploadFile" @uploadFileList="getUploadFileList" accept="image,pdf" folder="report"></uploadFile>
    <uploadHealth ref="uploadHealth" :relationId="uploadHealthData.relationId" :idCard="uploadHealthData.idCard"></uploadHealth>
    <viewPdf ref="viewPdf" :pdfUrl="pdfUrl" :isPrint="isPrint"></viewPdf>
    <linkTel ref="linkTel" :dataInfo="linkTelInfo"></linkTel>

    <el-dialog title="批量生成结果" :visible.sync="RBResultDialogVisible" width="30%" style="margin-top: 17vh" center>
      <div class="RBresult-picker-div">
        <p>已选择的报告单个数：</p>
        <p>{{ selectIds.length }}</p>
      </div>

      <div class="RBresult-picker-div">
        <p>请选择生成结果时间：</p>
        <el-date-picker
          v-model="RBResultPicker"
          type="datetime"
          placeholder="请选择生成结果时间"
          align="right"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="RBResultPickerOptions"
        >
        </el-date-picker>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="RBResultHandleClick()">确 定</el-button>
        <el-button @click="RBResultDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 财务备注 -->
    <el-dialog title="财务备注" :visible.sync="financeRemarkVisible" width="500px" center>
      <div style="position: relative">
        <el-button class="clear" type="danger" circle plain @click="confirmFinanceRemark(0)">清除</el-button>
        <el-input type="textarea" v-model="financeRemark" rows="7"> </el-input>
      </div>
      <template slot="footer">
        <el-button @click.native="financeRemarkVisible = false"> 取消 </el-button>
        <el-button type="primary" @click.native="confirmFinanceRemark"> 确定 </el-button>
      </template>
    </el-dialog>

    <!-- 批量修改医检机构 -->
    <el-dialog :visible.sync="institutionModifyVisible" title="批量修改医检机构" center width="400px">
      <div style="text-align: center">
        <el-select v-model="institutionModifyId" placeholder="请选择医检" clearable>
          <el-option v-for="item in institutionList" :label="item.label" :value="item.value" :key="item.value"> </el-option>
        </el-select>
      </div>
      <template slot="footer">
        <el-button @click.native="institutionModifyVisible = false"> 取消 </el-button>
        <el-button type="primary" @click.native="confirmBatchModifyInstitution"> 确定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import * as constants from '@/constants/constants';
import uploadFile from '@/components/UploadFile';
import uploadHealth from '@/components/UploadHealth';
import importExcel from '@/excel/importExcel';
import viewPdf from '@/components/viewPdf';
import linkTel from '@/components/LinkTel';
import InstitutionSelect from '@/components/InstitutionSelect';
import BatchAddReport from '@/components/BatchAddhsReport';
import BatchImport from '@/components/BatchhsImport';
import BatchEditCollect from '@/components/BatchEdithsCollect';
import { FORMAT_DATE_YYYY_MM_DD } from '@/constants/constants';
import { mapGetters, mapActions } from 'vuex';
import axios from 'axios';
import InstitutionApi from '@/api/institution/institution';
import CollectApi from '@/api/collect/collect';
import HospitalApi from '@/api/institution/hospital';
import OfficeApi from '@/api/institution/office';
import ReportApi from '@/api/hsReport/hsReport';
import DoctorApi from '@/api/institution/doctor';
import { getStorage } from '@/utils/auth';
import Clipboard from 'clipboard';
import * as stn from '@/constants/storeName';
import EquipApi from '@/api/equip/equip';

export default {
  name: 'hsReportManagement',
  inject: ['reload'], //注入局部刷新
  metaInfo: {
    meta: [
      {
        httpEquiv: 'Content-Security-Policy',
        content: 'upgrade-insecure-requests',
      },
    ],
  },
  data() {
    return {
      reportList: [],
      reportDataList: [],
      selectIds: [],
      selectReportList: [],
      userInfo: {},
      userRelation: {},
      userRole: '',
      pdfUrl: '',
      linkTelInfo: {},
      reportId: 0,
      addHelpRelationId: null,
      addItemReportId: null,
      isPrint: false,
      RBResultDialogVisible: false, //批量报告单打印弹框
      RBResultPicker: new Date(), //批量打印时间
      RBResultPickerOptions: {
        //批量打印时间快捷选项
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            },
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            },
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            },
          },
        ],
      },
      institutionModifyVisible: false, //医检机构批量修改弹框
      institutionModifyId: '', //批量修改的医检机构id
      listLoading: true, // 列表加载loading
      pageLoading: false, // 页面加载loading
      reportStateType: '', //状态标签默认样式
      importUrl: '', //导入的文件上传地址，因为只是选择不需要上传,所以这里固定为空就好了
      filters: {
        reportId: '',
        queryCode: '',
        searchCode: '',
        patientQuery: '',
        userId: '', //收样员id
        hospitalId: '',
        officeId: '',
        doctorId: '',
        institutionId: '',
        itemName: '',
        reportState: '',
        resultState: '',
        abnormalState: '',
        printState: '',
        state: '1',
        applyId: '',
        date: [],
      },

      uploadAccept: 0, // 上传的文件类型 0.all 1.pdf 2.img 3.video 4.excel
      uploadData: {
        reportId: '',
        reportIdList: [],
        uploadFiles: [],
      },
      uploadHealthData: {
        relationId: null,
        idCard: '',
      },
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      collectList: [],
      hospitalList: [],
      officeList: [],
      doctorList: [],
      institutionList: [],
      reviewStatue: [
        { label: '未收取', value: 0 },
        { label: '已收取', value: 5 },
        { label: '已送达', value: 10 },
        { label: '检测中', value: 15 },
        { label: '已出结果', value: 20 },
        { label: '取消中', value: 18 },
        { label: '已取消', value: 19 },
      ],
      abnormalStatue: [
        { label: '条码号异常', value: 1 },
        { label: '姓名/身份证异常', value: 2 },
        { label: '年龄/性别异常', value: 3 },
        { label: '多条结果', value: 4 },
        // { label: '结果未出', value: 5 },
        // { label: '结果时间太久，需要去对于官网查询', value: 6 },
        { label: '报告单结果未全出', value: 7 },
        { label: '认证错误', value: 8 },
        { label: '阳性', value: 9 },
      ],
      agenciesStatue: [
        { label: '未打印', value: 0 },
        { label: '已打印', value: 1 },
      ],
      resultStatue: [
        { label: '检测中', value: 0 },
        { label: '已出结果', value: 1 },
      ],

      permissionAdd: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_SEE',
      permissionBack: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_BACK',
      permissionEdit: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_EDIT',
      permissionUpload: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_UPLOAD',
      permissionViewSpecimen: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_VIEW_SPECIMEN',
      permissionUpStatus: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_DELETE',
      permissionLinkDoctor: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_LINK_DOCTOR',
      permissionHelp: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_HELP',
      permissionResume: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_RESUME',
      permissionPrint: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_PRINT',
      permissionBatchPrint: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_BATCH_PRINT',
      permissionBatchDownload: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_BATCH_DOWNLOAD',
      permissionBatchSetCollect: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_BATCH_SET_COLLECT',
      permissionBatchCreateResult: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_BATCH_CREATE_RESULT',
      permissionRefreshItem: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_REFRESH_ITEM',
      permissionDelivered: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_DELIVERED',
      permissionReceived: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_RECEIVED',
      permissionCollect: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_COLLECT',
      permissionDownload: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_DOWNLOAD',
      permissionExport: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_EXPORT',
      permissionFinanceRemark: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_FINANCE_REMARK',
      permissionModifyInstitution: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_MODIFY_INSTITUTION',
      permissionBatchDelete: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_BATCH_DELETE',
      permissionSendMessage: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_SEND_MESSAGE',
      permissionStateExport: 'SYSTEM_MANAGER_HSREPORT_INFO_LIST_STATE_EXPORT',
      // 财务备注弹框
      financeRemarkVisible: false,
      financeRemarkReportId: '',
      financeRemark: '',
      excelData: {},
      allList: [],
    };
  },
  computed: {
    ...mapGetters([]),
  },
  components: {
    // 引入组件
    uploadFile,
    InstitutionSelect,
    viewPdf,
    linkTel,
    uploadHealth,
    BatchEditCollect,
    BatchAddReport,
    BatchImport,
  },
  created() {
    this.init();
    //绑定事件
    window.addEventListener('keydown', this.keyDown);
  },
  mounted() {
    // 为了实现手机端下拉框可以打字搜索
    this.$Utils.removeSelectReadOnly();
  },
  activated() {
    if (this.$route.meta.keepAlive) {
      this.listReport();
    }
    let linkType = this.$route.query.linkType;
    if (linkType) {
      this.$refs.searchForm.resetFields();
      this.init();
    }
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      let _this = this;
      _this.listLoading = true;
      _this.userInfo = getStorage(stn.USER_INFO);
      _this.userRelation = getStorage(stn.USER_RELATION);
      // 根据用户角色，设置定好的查询条件
      if (_this.userInfo) {
        _this.userRole = _this.userInfo.userRole;
        if (_this.userRole == 2) {
          // 医生用户 - 默认查询条件:已出结果未打印
          //this.filters.reportState = 20;
          //this.filters.resultState = 1;
          //this.filters.printState = 0;
          _this.listInstitution();
          // 如果是医生用户，默认查询与之关联的医院信息
          _this.filters.hospitalId = _this.userRelation.hospitalId;
          _this.listOffice();
        } else if (_this.userRole == 3) {
          // 医检用户 - 默认查询条件：检测中
          _this.filters.resultState = 0;
          //this.filters.reportState = 10;
          //this.filters.reportStateLess = 20;
          _this.listHospital();
        } else {
          _this.listInstitution();
          _this.listCollect();
          _this.listHospital();
        }
      }
      _this.initDate();
      // 从首页跳过来的
      let linkType = _this.$route.query.linkType;
      if (linkType) {
        if (linkType === 1) {
          // 未打印报告单
          _this.filters.reportState = 20;
          _this.filters.printState = 0;
        } else if (linkType === 2) {
          // 今日新增报告单
          let begin = new Date();
          begin.setHours(0);
          begin.setMinutes(0);
          begin.setSeconds(0);
          let end = new Date();
          end.setHours(23);
          end.setMinutes(59);
          end.setSeconds(59);
          _this.filters.date = [begin, end];
          _this.filters.reportState = '';
          _this.filters.printState = '';
          _this.filters.resultState = '';
        } else if (linkType === 3) {
          // 待处理报告单（医检）
          //this.filters.reportState = 10;
          //this.filters.reportStateLess = 20;
          _this.filters.resultState = 0;
        }
      }
      // 从请求帮助列表跳转过来
      /*if (this.$route.query.reportId){
        this.filters.reportId = this.$route.query.reportId
      }*/

      _this.listReport();
      _this.getTableHeight();
    },

    cancelReadOnly(onOff) {
      this.$nextTick(() => {
        if (!onOff) {
          const { select } = this.$refs;
          const input = select.$el.querySelector('.el-input__inner');
          input.removeAttribute('readonly');
        }
      });
    },
    initDate() {
      let begin = new Date();
      begin.setHours(0);
      begin.setMinutes(0);
      begin.setSeconds(0);
      begin.setMonth(begin.getMonth() - 1);
      let end = new Date();
      end.setHours(23);
      end.setMinutes(59);
      end.setSeconds(59);
      this.filters.date = [begin, end];
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.initDate();
      this.onSearch();
    },
    RBResultHandleClick() {
      var _this = this;
      // _this.pageLoading = true;
      let reportEndTimes = _this.$Utils.formatDate(_this.RBResultPicker, 'yyyy-MM-dd hh:mm:ss');
      this.RBResultDialogVisible = false;
      _this.$notify.info({
        title: '提示',
        message: '生成结果中，请等待',
      });
      ReportApi.batchCreateResult({
        reportIdList: _this.selectIds,
        reportEndTime: reportEndTimes,
      }).then((res) => {
        // if (res.status == 0) {
        // _this.$Utils.notifySuccess();
        // _this.onSearch();
        // } else {
        // _this.$notify.error({
        //   title: message.TITLE_ERROR,
        //   message: "生成失败，请重试"
        // });
        // }
        // _this.pageLoading = false;
      });
      _this.onSearch();
    },
    /**
     * 复制项目名称
     */
    copyitemName() {
      var clipboard = new Clipboard('.copy_itemName');
      clipboard.on('success', (e) => {
        this.$Utils.messageSuccess('复制成功');
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$Utils.messageError('该浏览器不支持自动复制');
        // 释放内存
        clipboard.destroy();
      });
    },
    /**
     * 复制平台条码号
     */
    copyMyReportCode() {
      var clipboard = new Clipboard('.copy_myReportCode');
      clipboard.on('success', (e) => {
        this.$Utils.messageSuccess('复制成功');
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$Utils.messageError('该浏览器不支持自动复制');
        // 释放内存
        clipboard.destroy();
      });
    },
    /**
     * 复制医检条码号
     */
    copyInsReportCode() {
      var clipboard = new Clipboard('.copy_insReportCode');
      clipboard.on('success', (e) => {
        this.$Utils.messageSuccess('复制成功');
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$Utils.messageError('该浏览器不支持自动复制');
        // 释放内存
        clipboard.destroy();
      });
    },
    /**
     * 复制编号
     */
    copyReportCode() {
      var clipboard = new Clipboard('.copy_reportCode');
      clipboard.on('success', (e) => {
        this.$Utils.messageSuccess('复制成功');
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$Utils.messageError('该浏览器不支持自动复制');
        // 释放内存
        clipboard.destroy();
      });
    },
    formatSex(cellValue) {
      if (cellValue === 1) {
        return '男';
      } else if (cellValue === 2) {
        return '女';
      }
    },
    formatAbnormalState(row, column, cellValue) {
      if (cellValue === 1) {
        return '条码号异常';
      } else if (cellValue === 2) {
        return '姓名/身份证异常';
      } else if (cellValue === 3) {
        return '年龄/性别异常';
      } else if (cellValue === 4) {
        return '多条结果';
      }
    },
    formatPrintState(cellValue) {
      if (cellValue === 0) {
        return '未打印';
      } else if (cellValue === 1) {
        return '已打印';
      }
    },
    formatPrintStateType(cellValue) {
      if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    formatReportState(cellValue) {
      if (cellValue === 0) {
        return '未收取';
      } else if (cellValue === 5) {
        return '已收取';
      } else if (cellValue === 10) {
        return '已送达';
      } else if (cellValue === 12) {
        return '已收到';
      } else if (cellValue === 15) {
        return '检测中';
      } else if (cellValue === 17) {
        return '已出部分结果';
      } else if (cellValue === 20) {
        return '已出结果';
      }
    },
    formatReportStateType(cellValue) {
      if (cellValue === 0) {
        return 'danger';
      } else if (cellValue === 5) {
        return 'success';
      } else if (cellValue === 10) {
        return '';
      } else if (cellValue === 12) {
        return '';
      } else if (cellValue === 15) {
        return 'warning';
      } else if (cellValue === 17) {
        return 'info';
      } else if (cellValue === 20) {
        return 'success';
      }
    },
    formatState(row, column, cellValue) {
      if (cellValue === -1) {
        return '删除';
      } else if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      } else if (cellValue == 2) {
        return '待审核';
      }
    },
    formatDate(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, FORMAT_DATE_YYYY_MM_DD);
    },
    formatDateTime(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, 'yyyy-MM-dd hh:mm:ss');
    },
    listCollect() {
      let _this = this;
      _this.loadingIns = true;
      let cond = { roleId: 4 }; // 暂不传入任何参数
      // collectNameList--/admin/listAdmin  获取收样员名字列表
      CollectApi.listCollectUserName(cond).then((res) => {
        setTimeout(() => {
          _this.loadingIns = false;
          _this.collectList = res.data.map((item) => {
            return {
              value: item.userId,
              label: item.userName,
            };
          });
        }, 200);
      });
    },
    listHospital() {
      let _this = this;
      _this.loadingIns = true;
      let cond = {
        hospitalType: 1,
      };
      HospitalApi.getHospitalNameList(cond).then((res) => {
        setTimeout(() => {
          _this.loadingIns = false;
          _this.hospitalList = res.data.map((item) => {
            return {
              value: item.hospitalId,
              label: item.hospitalName,
            };
          });
        }, 200);
      });
    },
    listOffice() {
      let _this = this;
      _this.loadingIns = true;
      _this.officeList = [];
      _this.filters.officeId = '';
      _this.doctorList = [];
      _this.filters.doctorId = '';
      let cond = {
        hospitalId: _this.filters.hospitalId,
      };
      OfficeApi.getOfficeNames(cond)
        .then((res) => {
          setTimeout(() => {
            _this.loadingIns = false;
            _this.officeList = res.data.map((item) => {
              return {
                value: item.officeId,
                label: item.officeName,
              };
            });
          }, 200);
        })
        .catch((error) => {
          _this.officeList = [];
          console.error(error);
        });
    },
    listDoctor() {
      let _this = this;
      _this.loadingIns = true;
      _this.doctorList = [];
      _this.filters.doctorId = '';
      let cond = {
        hospitalId: _this.filters.hospitalId,
        officeId: _this.filters.officeId,
      };
      DoctorApi.getDoctorNames(cond)
        .then((res) => {
          setTimeout(() => {
            _this.loadingIns = false;
            _this.doctorList = res.data.map((item) => {
              return {
                value: item.doctorId,
                label: item.doctorName,
              };
            });
          }, 200);
        })
        .catch((error) => {
          _this.doctorList = [];
          console.error(error);
        });
    },
    listInstitution(query) {
      let _this = this;
      let institutionName = !query || typeof query !== 'string' ? '' : query;
      _this.loadingIns = true;
      InstitutionApi.selectInsByUser(institutionName)
        .then((res) => {
          setTimeout(() => {
            _this.loadingIns = false;
            _this.institutionList = res.data.map((item) => {
              return {
                value: item.institutionId,
                label: item.institutionName,
              };
            });
          }, 200);
        })
        .catch((error) => {
          _this.institutionList = [];
          console.error(error);
        });
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listReport();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listReport();
    },
    handleClickEditor(row) {
      let _this = this;
      _this.$router.push({
        path: '/hsReport/hsReportEdit',
        query: { id: row.reportId },
      });
    },

    handleClickUpload(row) {
      let _this = this;
      _this.uploadAccept = 1;
      _this.uploadData.reportId = row.reportId;
      _this.uploadData.reportIdList = [];
      _this.$refs.uploadFile.handleCreate();
    },
    handleClickMergeUpload() {
      let _this = this;
      if (_this.selectReportList.length < 2) {
        _this.$Utils.messageError('请至少选择2个报告单进行合并');
        return;
      }
      let originCode = _this.selectReportList[0].originCode;
      let isCan = true;
      _this.selectReportList.forEach((item) => {
        if (item.originCode !== originCode) {
          _this.$Utils.messageError('请选择相同患者的报告单进行合并上传');
          isCan = false;
          return;
        }
      });
      if (isCan) {
        this.$confirm('确定合并报告单并上传结果吗？', message.TITLE_PROMPT, {}).then(() => {
          _this.uploadAccept = 1;
          _this.uploadData.reportId = '';
          _this.uploadData.reportIdList = this.selectIds;
          _this.$refs.uploadFile.handleCreate();
        });
      }
    },
    handleClickCollect(row) {
      let _this = this;
      _this.$confirm('是否收取该标本', message.TITLE_PROMPT, {}).then(() => {
        ReportApi.updateReportState({
          reportId: row.reportId,
          reportState: 5,
        })
          .then((res) => {
            //this.reportList.splice(index,1)
            _this.listReport();
          })
          .catch((error) => {
            console.error(error);
          });
      });
    },
    handleClickDelivered(row) {
      let _this = this;
      _this.$confirm('是否送达该标本', message.TITLE_PROMPT, {}).then(() => {
        ReportApi.updateReportState({
          reportId: row.reportId,
          reportState: 10,
        })
          .then((res) => {
            //this.reportList.splice(index,1)
            _this.listReport();
          })
          .catch((error) => {
            console.error(error);
          });
      });
    },
    handleClickReceived(row) {
      let _this = this;
      _this.$confirm('是否确认已收到该标本', message.TITLE_PROMPT, {}).then(() => {
        ReportApi.updateReportState({
          reportId: row.reportId,
          reportState: 12,
        })
          .then((res) => {
            //this.reportList.splice(index,1)
            _this.listReport();
          })
          .catch((error) => {
            console.error(error);
          });
      });
    },

    handleClickViewSpecimen(row) {
      let _this = this;
      if (!row.syUserId) {
        _this.$notify.error({
          title: message.TITLE_PROMPT,
          message: '该报告暂未关联收样员，请先设置收样员',
        });
        return;
      }
      // 查询该收样员是否绑定标本箱
      EquipApi.getIdBySyUserId({
        syUserId: row.syUserId,
      }).then((res) => {
        if (res.data) {
          _this.$router.push({
            path: '/equip/boxDetail',
            query: { id: res.data, syUserId: row.syUserId },
          });
        } else {
          _this.$Utils.notifyError('未找到对应的标本箱');
        }
      });
    },

    // pdf上传
    getUploadFileList(val) {
      ////debugger
      let _this = this;
      if (!val) {
        _this.$Utils.messageError('请选择pdf上传');
        return;
      }
      _this.uploadData.uploadFiles = val;
      if (_this.uploadData.reportId) {
        ReportApi.addReportPdf(_this.uploadData)
          .then((res) => {
            _this.$Utils.notifySuccess();
            _this.listReport();
          })
          .catch((error) => {
            _this.$Utils.notifyError('上传失败，请稍后重试');
          });
      } else if (!_this.uploadData.reportId && _this.uploadData.reportIdList.length > 0) {
        ReportApi.addReportMerge(this.uploadData).then((res) => {
          _this.$Utils.notifySuccess();
          _this.listReport();
        });
      }
      //this.listReport()
    },
    changeSelect(val) {
      this.selectIds = [];
      for (let i = 0; i < val.length; i++) {
        this.selectIds.push(val[i].reportId);
      }
      this.selectReportList = val;
    },
    handleClickForPrint() {
      let _this = this;
      if (_this.isPrint) {
        _this
          .$confirm('是否已打印报告单结果？', message.TITLE_PROMPT, {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
          })
          .then(() => {
            let param;
            if (_this.reportId > 0) {
              param = { reportId: _this.reportId };
            } else {
              if (_this.selectIds.length > 0) {
                param = { reportIds: _this.selectIds.toString() };
              }
            }
            ReportApi.getReportPrint(param).then((res) => {
              // console.log("打印成功")
              _this.getReportUnprintCount();
            });
          });
      }
    },
    handleClickBatchPrint() {
      let _this = this;
      if (_this.selectIds.length > 0) {
        this.$confirm('是否批量打印' + _this.selectIds.length + '个报告单？', message.TITLE_PROMPT, {}).then(() => {
          ReportApi.getReportBatchPrint({
            reportIds: _this.selectIds.toString(),
          }).then((res) => {
            if (res.data) {
              _this.isPrint = true;
              _this.reportId = 0;
              _this.pdfUrl = res.data;
              this.$refs.viewPdf.handleCreate();
              //_this.$OpenUrl(res.data);
              //_this.getReportUnprintCount();
            } else {
              _this.$notify.error({
                title: message.TITLE_ERROR,
                message: '未上传报告单结果',
              });
            }
          });
        });
      } else {
        _this.$notify.error({
          title: message.TITLE_ERROR,
          message: '请选择你要打印的报告单！',
        });
      }
    },
    handleClickBatchCollect() {
      // 批量编辑收收样员
      let _this = this;
      if (_this.selectIds.length > 0) {
        _this.$refs.batchEditCollect.handleCreate(this.selectIds);
      } else {
        this.$message({
          message: '至少选择一条数据！',
          type: 'error',
        });
      }
    },
    handleClickPrint(row) {
      //_this.$print(this.$refs.print123)   打印指定区域
      if (row.reportState != 20) {
        return;
      }
      let _this = this;
      ReportApi.getReport({ reportId: row.reportId }).then((res) => {
        if (res.data.reportFileUrl) {
          _this.isPrint = true;
          _this.reportId = row.reportId;
          _this.pdfUrl = res.data.reportFileUrl;
          this.$refs.viewPdf.handleCreate();
        } else {
          _this.$notify.error({
            title: message.TITLE_ERROR,
            message: '未上传报告单结果',
          });
        }
      });
    },
    getReportUnprintCount() {
      ReportApi.getUnPrintReportCount({})
        .then((res) => {
          sessionStorage.setItem('unprintCount', res.data);
        })
        .catch((error) => {});
    },
    handleClickDownload(row) {
      let _this = this;
      let url = process.env.BASE_API + constants.hsReportDown + '?reportId=' + row.reportId;
      axios
        .get(url, {
          //url: 接口地址
          responseType: `arraybuffer`, //一定要写
        })
        .then((res) => {
          if (res.status == 200) {
            let blob = new Blob([res.data], {
              //type: `application/msword` //word文档为msword,pdf文档为pdf
              type: `application/pdf`, //word文档为msword,pdf文档为pdf
            });
            let objectUrl = window.URL.createObjectURL(blob);
            let link = document.createElement('a');
            let fName = row.patientName + row.reportCode; //下载文件的名字
            link.href = objectUrl;
            //link.setAttribute("download", fName);
            link.download = fName;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link); // 下载完成移除元素
            window.URL.revokeObjectURL(objectUrl); // 释放掉blob对象
          } else {
            _this.$notify.error({
              title: message.TITLE_ERROR,
              message: '下载失败',
            });
          }
        });
    },

    handleClickBatchDownload() {
      let _this = this;
      //let url = process.env.BASE_API+constants.reportBatchDown;
      if (_this.selectIds.length > 0) {
        this.$confirm('是否批量下载' + _this.selectIds.length + '个报告单？', message.TITLE_PROMPT, {}).then(() => {
          let ids = _this.selectIds.toString();
          _this.$Utils.downloadFiles(ids, constants.hsReportBatchDown);
        });
      } else {
        _this.$Utils.messageError('请选择你要下载的报告单！');
      }
    },
    handleClickBack(row) {
      let _this = this;
      this.$confirm('是否撤回该报告单已上传的文件', message.TITLE_PROMPT, {}).then(() => {
        ReportApi.getReportback({ reportId: row.reportId }).then((res) => {
          _this.listReport();
        });
      });
    },
    handleIsDisable(row, state) {
      let _this = this;
      this.$confirm('是否' + (state == -1 ? '删除' : '恢复') + '该报告单', message.TITLE_PROMPT, {}).then(() => {
        ReportApi.deleteReport({
          reportId: row.reportId,
          state: state,
        }).then((res) => {
          _this.listReport();
        });
      });
    },

    handleClickAddBatch() {
      // 批量新增报告单 - 通过弹出框的形式
      let _this = this;
      _this.$refs.batchAddReport.handleCreate(this.selectIds);
      _this.$refs.batchAddReport.getUserRole(this.userRole);
    },
    // 批量导入
    handleBatchImport() {
      let _this = this;
      _this.$refs.BatchImport.clearTable();
      _this.$refs.BatchImport.handleCreate(this.selectIds);
      _this.$refs.BatchImport.getUserRole(this.userRole);
    },

    handleClickAdd() {
      let _this = this;
      _this.$router.push('/hsReport/hsReportAdd');
    },
    handleClickDetail(row) {
      let _this = this;
      _this.$router.push({
        path: '/hsReport/hsReportDetail',
        query: { id: row.reportId },
      });
    },
    handleClickRefreshItemName(type) {
      // 刷新项目
      ReportApi.refreshReportItem({ day: 90 }).then((res) => {
        if (res.status == 0 && type == 1) {
          this.$Utils.notifySuccess();
        }
      });
    },
    handleClickBatchCreateResult() {
      let _this = this;
      if (_this.selectIds.length > 0) {
        this.RBResultDialogVisible = true;
        this.RBResultPicker = new Date();
      } else {
        _this.$notify.error({
          title: message.TITLE_ERROR,
          message: '请选择你要生成结果的报告单！',
        });
      }
    },

    // 批量修改医检机构
    handleBatchModifyInstitution() {
      if (this.selectIds.length == 0) {
        this.$message.error('请至少选择一项');
        return;
      }
      this.institutionModifyVisible = true;
      this.institutionModifyId = '';
    },
    // 确定批量修改医检机构
    confirmBatchModifyInstitution() {
      if (!this.institutionModifyId) {
        this.$message.error('请选择医检机构');
        return;
      }
      this.$confirm('确认批量修改医检机构吗？', '提示', {
        type: 'warning',
      }).then((res) => {
        let params = {
          ids: this.selectIds,
          id: this.institutionModifyId,
          state: 1,
        };
        ReportApi.batchUpdateInstitution(params).then((res) => {
          this.$message.success('操作成功');
          this.institutionModifyVisible = false;
          this.institutionModifyId = '';
          this.listReport();
        });
      });
    },
    //批量删除核酸报告单
    handleBatchDelete() {
      if (this.selectIds.length == 0) {
        this.$message.error('请至少选择一项');
        return;
      }
      this.$confirm('确认批量删除核酸报告单吗？', '提示', {
        type: 'warning',
      }).then((res) => {
        let params = {
          ids: this.selectIds,
          state: -1,
        };
        ReportApi.bacthDeleteHsReport(params).then((res) => {
          this.$message.success('删除成功！');
          this.listReport();
        });
      });
    },

    // 短信通知
    hanldeSendMessage() {
      if (this.selectIds.length == 0) {
        this.$message.error('请至少选择一项');
        return;
      }
      this.$confirm('确认批量发送短信吗？', '提示', {}).then((res) => {
        let params = {
          ids: this.selectIds,
        };
        ReportApi.batchSendMessage(params).then((res) => {
          this.$message.success('发送成功！');
          this.listReport();
        });
      });
    },
    // 导入
    handleChange(file) {
      this.fileTemp = file.raw;
      if (this.fileTemp) {
        if (this.fileTemp.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || this.fileTemp.type === 'application/vnd.ms-excel') {
          // 开始导入
          importExcel(file, 0, ['strings'])
            .then((res) => {
              let arr = res.map((item) => item.strings);
              this.$confirm('确认上传-' + file.name + '-表格数据？', '提示', {}).then((res) => {
                ReportApi.batchUpdateHsState({ strings: arr }).then((res) => {
                  this.$message.success('上传成功！');
                  this.listReport();
                });
              });
              //导入的表格转换时往每一列添加一个编辑标识属性
              // let resList = res;
              // let index = 1;
              // for (let i = 0; i < resList.length; i++) {
              //   resList[i].iseditor = false;
              //   resList[i].index = index++;
              // }
              // this.dataList = resList;
            })
            .catch((err) => {
              this.$message.error(err);
            });
        } else {
          this.$message({
            type: 'error',
            message: '附件格式错误，请删除后重新上传！',
          });
        }
      } else {
        this.$message({ type: 'warning', message: '请上传附件！' });
      }
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },
    onSearch() {
      this.listLoading = true;
      this.page.pageNo = 1;
      this.listReport();
    },
    listReport() {
      let _this = this;
      let cond = {
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize,
        queryCode: _this.filters.queryCode,
        searchCode: _this.filters.searchCode,
        itemName: _this.filters.itemName,
        syUserId: _this.filters.userId,
        hospitalId: _this.filters.hospitalId,
        officeId: _this.filters.officeId,
        doctorId: _this.filters.doctorId,
        applyId: _this.filters.applyId,
        institutionId: _this.filters.institutionId,
        state: _this.filters.state,
        patientQuery: _this.$Utils.isNullStrict(_this.filters.patientQuery) ? null : _this.filters.patientQuery,
        printState: _this.$Utils.isNullStrict(_this.filters.printState) ? null : _this.filters.printState,
        reportState: _this.$Utils.isNullStrict(_this.filters.reportState) ? null : _this.filters.reportState,
        resultState: _this.$Utils.isNullStrict(_this.filters.resultState) ? null : _this.filters.resultState,
        abnormalState: _this.$Utils.isNullStrict(_this.filters.abnormalState) ? null : _this.filters.abnormalState,
      };
      if (this.filters.date && this.filters.date.length == 2) {
        cond.createDateBegin = this.$Utils.formatDate(this.filters.date[0], 'yyyy-MM-dd hh:mm:ss');
        cond.createDateEnd = this.$Utils.formatDate(this.filters.date[1], 'yyyy-MM-dd hh:mm:ss');
      }

      // 将查询条件缓存起来
      //setLocalStorage(stn.REPORT_MANAGEMENT_PARAM,cond)
      ReportApi.getReportsList(cond)
        .then((res) => {
          _this.listLoading = false;
          _this.reportList = res.data.list;
          _this.allList = res.data.list;
          _this.page.pageTotal = res.data.total;
        })
        .catch((error) => {
          _this.listLoading = false;
          console.error(error);
        });
    },

    sureDoctorClick() {
      _this.$refs.doctorForm.validate((valid) => {
        if (valid) {
          _this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {}).then(() => {
            // //debugger
            if (_this.doctorForm.doctorId) {
              _this.alterDoctor();
            } else {
              _this.addDoctor();
            }
          });
        }
      });
    },
    alterDoctor() {
      let _this = this;
      DoctorApi.editDoctor(this.doctorForm).then((data) => {
        this.dialogVisible = false;
        _this.listReport();
        _this.$Utils.notifySuccess();
      });
    },
    addDoctor() {
      DoctorApi.addDoctor(this.doctorForm);
      let _this = this.then((data) => {
        this.dialogVisible = false;
        _this.listReport();
        _this.$Utils.notifySuccess();
      });
    },
    handleClickExport(groupBy) {
      let _this = this;
      this.$confirm('此操作将导出excel文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          _this.pageLoading = true;
          // 导出前先刷新项目
          _this.handleClickRefreshItemName(2);
          let cond = {
            groupBy: groupBy,
            queryCode: _this.filters.queryCode,
            searchCode: _this.filters.searchCode,
            itemName: _this.filters.itemName,
            applyId: _this.filters.applyId,
            hospitalId: _this.filters.hospitalId,
            officeId: _this.filters.officeId,
            doctorId: _this.filters.doctorId,
            institutionId: _this.filters.institutionId,
            pageNo: _this.page.pageNo,
            pageSize: _this.page.pageSize,
          };
          if (this.filters.date && this.filters.date.length == 2) {
            cond.createDateBegin = this.$Utils.formatDate(this.filters.date[0], 'yyyy-MM-dd hh:mm:ss');
            cond.createDateEnd = this.$Utils.formatDate(this.filters.date[1], 'yyyy-MM-dd hh:mm:ss');
          }
          let patientQuery = _this.filters.patientQuery;
          let printState = _this.filters.printState;
          let reportState = _this.filters.reportState;
          let resultState = _this.filters.resultState;
          let abnormalState = _this.filters.abnormalState;
          let state = _this.filters.state;
          if (patientQuery !== undefined && patientQuery !== null && patientQuery !== '') {
            cond.patientQuery = patientQuery;
          }
          if (printState !== undefined && printState !== null && printState !== '') {
            cond.printState = printState;
          }
          if (reportState !== undefined && reportState !== null && reportState !== '') {
            cond.reportState = reportState;
          }
          if (resultState !== undefined && resultState !== null && resultState !== '') {
            cond.resultState = resultState;
          }
          if (abnormalState !== undefined && abnormalState !== null && abnormalState !== '') {
            cond.abnormalState = abnormalState;
          }
          if (state !== undefined && state !== null && state !== '') {
            cond.state = state;
          }
          ReportApi.getReportExport(cond).then((res) => {
            if (res.data && res.data.length > 0) {
              let result = res.data;
              result.forEach((item) => {
                if (item.source) {
                  /* 1是普通新增，5是表格导入 */
                  item.source = item.source == 1 ? '普通新增' : '表格导入';
                }

                if (item.patientSex) {
                  item.patientSexName = this.formatSex(item.patientSex);
                }
                item.reportStateName = this.formatReportState(item.reportState);
                if (item.abnormalState) {
                  item.abnormalStateName = this.formatAbnormalState(item.abnormalState);
                }
              });
              _this.excelData = result;
              _this.pageLoading = false;
              this.export2Excel(groupBy ? 1 : 0);
            } else {
              this.$notify.error({
                title: message.TITLE_ERROR,
                message: '未找到可导出的数据，请重新查询',
              });
            }
          });
        })
        .catch(() => {
          console.error(error);
        });
    },
    export2Excel(groupBy) {
      // 这里的groupBy表示是否分组
      let that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../excel/Export2Excel'); //这里必须使用绝对路径
        const tHeader = [
          '送检时间',
          '编号',
          '平台条码号',
          '采样编号',
          '患者姓名',
          '患者性别',
          '患者年龄',
          '患者手机',
          '患者身份证',
          '地址',
          '职业',
          '项目名称',
          '医院名称',
          '科室名称',
          '医生姓名',
          '医检机构',
          '医检条码号',
          '当前收样员',
          '所有收样员',
          '上传结果用户',
          '报告单状态',
          '异常信息',
          '财务备注',
          '来源',
          '报告时间',
          '最新打印时间',
          '创建人',
          '创建时间',
          '修改人',
          '修改时间',
          '备注',
        ]; // 导出的表头名
        const filterVal = [
          'reportBeginTime',
          'reportCode',
          'myReportCode',
          'applyId',
          'patientName',
          'patientSexName',
          'patientAge',
          'patientPhone',
          'patientCard',
          'address',
          'job',
          'itemName',
          'hospitalName',
          'officeName',
          'doctorName',
          'institutionName',
          'insReportCode',
          'syUserName',
          'syUserNames',
          'uploadUserName',
          'reportStateName',
          'abnormalStateName',
          'financeRemark',
          'source',
          'reportEndTime',
          'reportPrintTime',
          'createUserName',
          'createDate',
          'modifyUserName',
          'modifyDate',
          'remark',
        ]; // 导出的表头字段名
        // 如果是合并导出
        if (groupBy) {
          tHeader.splice(
            tHeader.findIndex((item) => item == '来源'),
            1,
          );
          filterVal.splice(
            filterVal.findIndex((item) => item == 'source'),
            1,
          );
        }

        const list = that.excelData;
        const data = that.formatJson(filterVal, list);
        //let time1,time2 = '';
        //export_json_to_excel(tHeader, data, `[${time1}-${time2}]医生管理列表`);// 导出的表格名称，根据需要自己命名
        let currentTime = this.$Utils.formatDate(new Date(), 'yyyy-MM-dd');
        export_json_to_excel(tHeader, data, `康来核酸报告单数据_${currentTime}`); // 导出的表格名称，根据需要自己命名
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    financeRemarkDialog(id) {
      ReportApi.getFinanceRemark({ reportId: id }).then((res) => {
        this.financeRemarkReportId = id;
        this.financeRemark = res.data;
        this.financeRemarkVisible = true;
      });
    },
    confirmFinanceRemark(type = 0) {
      let params = {
        reportId: this.financeRemarkReportId,
        remark: type ? this.financeRemark : '',
      };
      let tip = type ? '确认提交修改吗？' : '确认清除财务备注吗？';
      this.$confirm(tip, '提示', {}).then((res) => {
        ReportApi.financeRemark(params).then((res) => {
          this.financeRemarkVisible = false;
          this.$message.success('操作成功');
        });
      });
    },
  },
  /*beforeRouteEnter(to,from,next){
    next(vm => {
      if (from.path == '/report/reportAdd' || from.path == '/report/reportEdit') {
        vm.init();
      }
    })
  }*/
};
</script>
<style scoped>
.RBresult-picker-div {
  display: flex;
  vertical-align: middle;
  margin: auto;
  width: 400px;
}
.RBresult-picker-div p {
  margin: 11px;
}
.print {
  width: 500px;
  height: 800px;
}
#copyBtn {
  background: none;
  border: none;
}
#copyBtn:hover {
  background: none;
  border: none;
}
.clear {
  position: absolute;
  z-index: 999;
  top: -65px;
  width: 35px;
  height: 35px;
  padding: 3px;
  font-size: 13px !important;
}
</style>
<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
